package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QQSMSUtils;
import com.ruoyi.system.domain.EmDamage;
import com.ruoyi.system.domain.EmRecord;
import com.ruoyi.system.domain.EmWarning;
import com.ruoyi.system.domain.EmWarningUser;
import com.ruoyi.system.domain.dto.CallUserDto;
import com.ruoyi.system.domain.dto.DamageInfo;
import com.ruoyi.system.domain.dto.StatisticsParamDTO;
import com.ruoyi.system.domain.dto.WarningUserDto;
import com.ruoyi.system.enums.WarningHandleEnum;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IEmWarningService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 预警信息Service业务层处理
 *
 * @author yangcan
 * @date 2023-03-07
 */
@Slf4j
@Service
public class EmWarningServiceImpl extends ServiceImpl<EmWarningMapper,EmWarning> implements IEmWarningService
{
    @Autowired
    private EmWarningMapper emWarningMapper;
    @Autowired
    private EmWarningUserMapper wuMapper ;
    @Autowired
    private SysUserMapper userMapper ;
    @Autowired
    private EmRecordMapper recordMapper ;
    @Autowired
    private EmDamageMapper damageMapper ;

    /**
     * 查询预警信息
     *
     * @param id 预警信息主键
     * @return 预警信息
     */
    @Override
    public EmWarning selectEmWarningById(Long id)
    {
        return emWarningMapper.selectById(id);
    }

    /**
     * 查询预警信息列表
     *
     * @param emWarning 预警信息
     * @return 预警信息
     */
    @Override
    public List<EmWarning> selectEmWarningList(EmWarning emWarning)
    {
        List<EmWarning> emWarnings = emWarningMapper.selectEmWarningList(emWarning);
        for (EmWarning warning : emWarnings) {
            warning.setIsHandleDescribe(WarningHandleEnum.getMessageByCode(Integer.valueOf(warning.getIsHandle() + "")));
        }
        return emWarnings;
    }

    /**
     * 新增预警信息
     *
     * @param emWarning 预警信息
     * @return 结果
     */
    @Override
    public int insertEmWarning(EmWarning emWarning)
    {
        emWarning.setCreateTime(DateUtils.getNowDate());
        Long recordId = emWarning.getRecordId();
        EmRecord emRecord = recordMapper.selectById(recordId);
        emRecord.setId(recordId);
        emRecord.setIsSend(1);
        recordMapper.updateById(emRecord) ;
        /**通知所有用户*/
        List<SysUser> users = userMapper.selectUserList(new SysUser());
        for (SysUser user : users) {
            try {
                QQSMSUtils.sendWarningMail(user.getEmail(),emRecord.getContext());
            } catch (Exception e) {
                e.printStackTrace();
                log.info("预警信息发送失败，失败信息为 ->{}",e.getMessage());
            }
        }
        if (!Objects.isNull(emWarning.getEmTypeId())){
            EmDamage damage = damageMapper.selectEmDamageById(emRecord.getEmTypeId());
            emWarning.setEmType(damage.getTypeName());
            emWarning.setEmName(damage.getName());
            emWarning.setHandleMethod(damage.getHandleMethod());
        }
        return emWarningMapper.insert(emWarning);
    }

    /**
     * 修改预警信息
     *
     * @param emWarning 预警信息
     * @return 结果
     */
    @Override
    public int updateEmWarning(EmWarning emWarning)
    {
        emWarning.setUpdateTime(DateUtils.getNowDate());
        emWarning.setCreateTime(null);
        if (!Objects.isNull(emWarning.getEmTypeId())){
            EmDamage damage = damageMapper.selectEmDamageById(emWarning.getEmTypeId());
            emWarning.setEmType(damage.getTypeName());
            emWarning.setEmName(damage.getName());
            emWarning.setHandleMethod(damage.getHandleMethod());
        }
        return emWarningMapper.updateById(emWarning);
    }

    /**
     * 批量删除预警信息
     *
     * @param ids 需要删除的预警信息主键
     * @return 结果
     */
    @Override
    public int deleteEmWarningByIds(Long[] ids)
    {
        return emWarningMapper.deleteEmWarningByIds(ids);
    }

    /**
     * 删除预警信息信息
     *
     * @param id 预警信息主键
     * @return 结果
     */
    @Override
    public int deleteEmWarningById(Long id)
    {
        return emWarningMapper.deleteEmWarningById(id);
    }

    @Override
    public void pullUserInfo(WarningUserDto dto) throws Exception {

        if (CollectionUtils.isEmpty(dto.getUsers())){
            throw new Exception("不能没有推送的人员信息！") ;
        }
        for (Long user : dto.getUsers()) {
            EmWarningUser userInfo = new EmWarningUser();
            userInfo.setUserId(user);
            userInfo.setWarningId(dto.getWarningId());
            try{
                wuMapper.insertEmWarningUser(userInfo) ;
            }catch (Exception e){
                log.info("推送给预警人员出错，信息为 ->{}",e.getMessage());
            }
        }
        EmWarning emWarning = new EmWarning();
        emWarning.setId(dto.getWarningId());
        emWarning.setIsHandle(1L);
        emWarning.setCreateTime(null);
        this.updateEmWarning(emWarning) ;


    }

    @Override
    public List<SysUser> getWarningUserInfo(Long id) {
        List<SysUser> list = new ArrayList<>();
        List<EmWarningUser> warningUsers = wuMapper.getUserListByWarningId(id) ;
        for (EmWarningUser warningUser : warningUsers) {
            SysUser sysUser = userMapper.selectUserById(warningUser.getUserId());
            sysUser.setIsNotice(warningUser.getIsNotice());
            sysUser.setIsNoticeDescribe(warningUser.getIsNotice() == 0 ? "未通知" : "已通知");
            list.add(sysUser) ;
        }
        return list;
    }

    @Override
    public void callUser(CallUserDto dto) throws Exception {
        if (Objects.isNull(dto) || Objects.isNull(dto.getId()) || Objects.isNull(dto.getUserId())){
            throw new Exception("必须选取呼叫人员信息!") ;
        }
        wuMapper.callUser(dto) ;

        SysUser sysUser = userMapper.selectUserById(dto.getUserId());
        if (Objects.isNull(sysUser)){
            throw new ServiceException("预警人员信息不能为空") ;
        }
        EmWarning emWarning = emWarningMapper.selectEmWarningById(dto.getId());
        if (Objects.isNull(emWarning)){
            throw new ServiceException("灾害信息不能为空") ;
        }
        QQSMSUtils.sendWarningToHandlePersonMail(sysUser.getEmail(),emWarning.getContext());
    }

    @Override
    public List<EmWarning> getMyWarning(EmWarning emWarning) {
        List<EmWarning> emWarnings = emWarningMapper.getMyWarning(emWarning);
        if (CollectionUtils.isEmpty(emWarnings)){
            return emWarnings ;
        }
        for (EmWarning warning : emWarnings) {
            if (!Objects.isNull(warning) && !Objects.isNull(warning.getIsHandle())){
                warning.setIsHandleDescribe(WarningHandleEnum.getMessageByCode(Integer.valueOf(warning.getIsHandle() + "")));
            }
        }
        return emWarnings;
    }

    @Override
    public Map<String, Object> getStatisticsInfo(StatisticsParamDTO dto) {
        LambdaQueryWrapper<EmWarning> wrapper = new LambdaQueryWrapper<>();
        if (CollectionUtils.isNotEmpty(dto.getTime())) {
            wrapper.between(EmWarning::getCreateTime,dto.getTime().get(0),dto.getTime().get(1)) ;
        }
        HashMap<String, Object> map = new HashMap<>();
        /**获取预警统计信息*/
        List<EmWarning> warningList = this.emWarningMapper.selectList(wrapper) ;
        List<EmDamage> damages = damageMapper.selectEmDamageList(new EmDamage()).stream().distinct().collect(Collectors.toList());
        HashMap<String, Integer> hashMap = new HashMap<>();
        for (EmDamage damage : damages) {
            hashMap.put(damage.getName(), 0) ;
            if(Objects.isNull(dto.getDamage())){
                dto.setDamage(damage.getId());
            }
        }
        for (EmWarning emWarning : warningList) {
            if (hashMap.containsKey(emWarning.getEmName())) {
                hashMap.put(emWarning.getEmName(),hashMap.get(emWarning.getEmName()) + 1) ;
            }
        }
        /**圆图数据*/
        List<EmWarning> warnings = warningList.stream().filter((w) -> (w.getEmTypeId().equals(dto.getDamage()))).collect(Collectors.toList());
        ArrayList<DamageInfo> list = new ArrayList<>();

        DamageInfo damageInfo = new DamageInfo();
        damageInfo.setValue(warnings.size() + "");
        damageInfo.setName(damages.stream().filter((d)->(d.getId().equals(dto.getDamage()))).findFirst().get().getName());
        list.add(damageInfo) ;

        WarningHandleEnum[] values = WarningHandleEnum.values();
        for (WarningHandleEnum value : values) {
            DamageInfo info = new DamageInfo();
            info.setName(value.getMessage());
            info.setValue(warnings.stream().filter((w)->(w.getIsHandle().equals((long) value.getCode()))).count() + "");
            list.add(info) ;
        }


        map.put("title",hashMap.keySet().toArray()) ;
        map.put("titleInfo",hashMap.values().toArray()) ;
        map.put("damageDataMap",list) ;

        return map;
    }

    @Override
    public void warningAllWorker(Long id) {
        List<EmWarningUser> list = wuMapper.getUserListByWarningId(id);
        if (CollectionUtils.isNotEmpty(list)) {
            for (EmWarningUser user : list) {
                user.setIsNotice(1) ;
                wuMapper.updateEmWarningUser(user) ;
                SysUser sysUser = userMapper.selectUserById(user.getUserId());
                EmWarning emWarning = emWarningMapper.selectEmWarningById(user.getWarningId());
                try {
                    QQSMSUtils.sendWarningToHandlePersonMail(sysUser.getEmail(),emWarning.getContext());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }else {
            throw new ServiceException("推送人员为空！") ;
        }


    }


}
